package fleekcli

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/pkg/errors"
	"github.com/pterm/pterm"
	"github.com/spf13/cobra"
	"github.com/ublue-os/fleek/fin"
)

func genDocsCmd() *cobra.Command {
	var genDocsCmd = &cobra.Command{
		Use:   "gen-docs <path>",
		Short: "[internal] generate documentation for the CLI",
		Long: "[internal] generates the documentation for the CLI's Cobra commands. " +
			"Docs are placed in the directory specified by <path>.",
		Hidden: true,
		Args:   cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {

			wd, err := os.Getwd()
			if err != nil {
				return errors.WithStack(err)
			}
			docsPath := filepath.Join(wd, args[0]) /* relative path */
			/*

				// We clear out the existing directory so that the doc-pages for
				// commands that have been deleted in the CLI will also be removed
				// after we re-generate the docs below
				/*
					err = os.RemoveAll(docsPath)
					if err != nil {
						return errors.WithStack(err)
					}

					// Ensure the directory exists
					err = os.MkdirAll(docsPath, 0755)
					if err != nil {
						return errors.WithStack(err)
					}

					rootCmd := cmd
					for rootCmd.HasParent() {
						rootCmd = rootCmd.Parent()
					}

					// Removes the line in the generated docs of the form:
					// ###### Auto generated by spf13/cobra on 18-Jul-2022
					rootCmd.DisableAutoGenTag = true
					filePrepender := func(filename string) string {
						name := filepath.Base(filename)
						base := strings.TrimSuffix(name, path.Ext(name))
						return fmt.Sprintf(fmTemplate, strings.Replace(base, "_", " ", -1), strings.Replace(base, "_", " ", -1))
					}
					linkHandler := func(name string) string {
						base := strings.TrimSuffix(name, path.Ext(name))
						return "/docs/cli/" + strings.ToLower(base) + "/"
					}
					return errors.WithStack(doc.GenMarkdownTreeCustom(rootCmd, docsPath, filePrepender, linkHandler))
			*/
			doc := fin.GenerateMarkdownDoc(cmd.Root())

			pterm.Fatal.PrintOnError(os.WriteFile(filepath.Join(docsPath, fmt.Sprintf("%s.md", cmd.Root().Name())), []byte(doc.Markdown), 0777))
			for _, subCmd := range cmd.Root().Commands() {
				if !subCmd.Hidden {
					doc := fin.GenerateMarkdownDoc(subCmd)
					fileName := strings.Replace(subCmd.CommandPath(), " ", "_", -1)

					pterm.Fatal.PrintOnError(os.WriteFile(filepath.Join(docsPath, fmt.Sprintf("%s.md", fileName)), []byte(doc.Markdown), 0777))

					for _, subSubCmd := range subCmd.Commands() {
						if !subSubCmd.Hidden {
							fileName := strings.Replace(subSubCmd.CommandPath(), " ", "_", -1)
							doc := fin.GenerateMarkdownDoc(subSubCmd)
							pterm.Fatal.PrintOnError(os.WriteFile(filepath.Join(docsPath, fmt.Sprintf("%s.md", fileName)), []byte(doc.Markdown), 0777))
						}
					}
				}
			}

			return nil
		},
	}

	return genDocsCmd
}
